#include <rtthread.h>
#include "finsh.h"
#include <board.h>
#include <dfs_posix.h>

u32 LE2BE(u8 *data,u8 len)
{
	u32 tmp=0;
    if(len >= 1) tmp  = (u32)data[0];
    if(len >= 2) tmp |= (u32)data[1]<<8;
    if(len >= 3) tmp |= (u32)data[2]<<16;
    if(len >= 4) tmp |= (u32)data[3]<<24;
	return tmp;
}

void u24_data_480_deal(u8 *src,u8 *targ)
{
	u16 i;
	for(i=0;i<480;i+=3)
	{
		*((u16 *)targ)++= (*(src+i)>>3)+(((u16)(*(src+i+1)))>>2<<5)+(((u16)(*(src+i+2)))>>3<<11);
	}
}

void show_bmp(const char *pathname)
{
	extern void ili9325_lcd_static_x_color_line(const char* pixels, int x, int y, rt_size_t size);	

	int fd;
	u8 buffer[480];
	u8 buffer1[320];
	u32 datasize;
	u16 x=0,y=0;

	fd=open(pathname,O_RDONLY,0);
    if(fd<0)
    {
        rt_kprintf("open file failed!\n");
		return;
    }
	read(fd,buffer,sizeof(buffer));
	
	if((buffer[0]==0x42)&&(buffer[1]==0x4d))
		rt_kprintf("\"$%s\" is a bmp pictrue\n",pathname);
	else
	{
		rt_kprintf("\"$%s\" is not a bmp pictrue\n",pathname);
		close(fd);
		return;
	}	
	rt_kprintf("bfSize is %d bytes\n",LE2BE(buffer+2,4));
	rt_kprintf("bfOffBits is %d bytes\n",LE2BE(buffer+10,4));
	rt_kprintf("biWidth is %d,biHeight is %d\n",LE2BE(buffer+18,4),LE2BE(buffer+22,4));
	rt_kprintf("biBitCount is %d \n",LE2BE(buffer+28,2)); 
	rt_kprintf("biSizeImage is %d \n",LE2BE(buffer+34,4)); 
	
	if((LE2BE(buffer+18,4)==320)&&(LE2BE(buffer+22,4)==240)&&(LE2BE(buffer+28,2)==24))
	{
		datasize=LE2BE(buffer+34,4);
		lseek(fd,LE2BE(buffer+10,4),DFS_SEEK_SET);
		while(datasize>=480)
		{
			read(fd,buffer,sizeof(buffer));
			datasize-=480;
			u24_data_480_deal(buffer,buffer1);
			ili9325_lcd_static_x_color_line(buffer1,x,y,160);
			y+=160;
			if(y>=320)
			{
				y=0;
				x++;
			}
		}
	}
	else
		rt_kprintf("can not show this picture\n");
	
	close(fd);	  
}


FINSH_FUNCTION_EXPORT(show_bmp, show bmp picture)
